package com.efounder.activity;


import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.efounder.adapter.CollectAdapter;
import com.efounder.bean.CollectList;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.MallRequestUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.utilcode.util.ToastUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import static com.efounder.utils.MallRequestUtil.GOOD_COLLECT_AOR;
import static com.efounder.utils.MallRequestUtil.GOOD_COLLECT_URL;

public class CollectionActivity extends BaseActivity {

    private String TAG = this.getClass().getSimpleName();
    private TextView tvTitle;
    private ImageView ivBack;
    private SmartRefreshLayout xRefreshView;
    private RecyclerView recyclerView;
    private LinearLayout llNetworkErrorView;
    private LinearLayout noCollection;

    private RecyclerView.LayoutManager mLayoutManager;
    private ArrayList<String> data = new ArrayList<>();
    private ArrayList<CollectList.CollectGoodsBean> collects;
    private int num = 0;
    private int pageSize = 10;
    private CollectAdapter mAdapter;
    private CollectList collectList;
    private Boolean isRefresh = true;
    private String goodbh = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collection);

        initView();

        collects = new ArrayList<>();
        init();
        tvTitle.setText(R.string.mail_my_collection);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        xRefreshView = (SmartRefreshLayout) findViewById(R.id.xRefreshView);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView_collect);
        llNetworkErrorView = (LinearLayout) findViewById(R.id.ll_network_error);
        noCollection = (LinearLayout) findViewById(R.id.no_collection);
    }

    public void getCollectGoods(String num, String pageSize) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("pageSize", pageSize);
        map.put("num", num);
        LoadingDataUtilBlack.show(CollectionActivity.this);
        MallRequestUtil.getRequest(TAG, GOOD_COLLECT_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                if (response != null && response.length() > 0) {
                    collects.clear();
                    initCommentData(response);
                }

            }


            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                llNetworkErrorView.setVisibility(View.VISIBLE);
            }
        });
    }

    private void initCommentData(String response) {
        try {
            Gson gson = new GsonBuilder().serializeNulls().create();
            collectList = gson.fromJson(response, CollectList.class);
            if (collectList.getResult().equals("success")) {
                if (collectList.getCollectGoods().size() > 0) {
                    collects.addAll(collectList.getCollectGoods());
                } else if (isRefresh) {
                    xRefreshView.setVisibility(View.GONE);
                    noCollection.setVisibility(View.VISIBLE);
                }
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
            }
            xRefreshView.finishRefresh();
            xRefreshView.finishLoadMore();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setAdapter() {
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mAdapter = new CollectAdapter(this, collects);
        mAdapter.setOnDeleteClickListener(new CollectAdapter.OnDeleteClickListener() {
            @Override
            public void onDelete(int position) {
                collects.remove(position);
                goodbh = collectList.getCollectGoods().get(position).getGoodId();
                removeCollect(goodbh);
            }
        });
        // 设置布局管理器
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter);
    }

    /**
     * 修改我的收藏数量
     */
    public void removeCollect(String goodbh) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("goodBhs", goodbh);
        map.put("operate", "remove");
        MallRequestUtil.getRequest(TAG, GOOD_COLLECT_AOR, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getString("result").equals("success")) {
                        getCollectGoods(String.valueOf(num), String.valueOf(pageSize));
                        mAdapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(CollectionActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtils.showShort(R.string.mall_collect_fail);
                }
            }

            @Override
            public void onFail(String error) {
                ToastUtils.showShort(R.string.mall_collect_fail);
            }
        });
    }

    private void init() {
        setAdapter();
        xRefreshView.setEnableLoadMore(true);
        xRefreshView.setEnableRefresh(true);
        xRefreshView.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                //               num += pageSize;
                getCollectGoods(String.valueOf(num), String.valueOf(pageSize));
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                collects.clear();
                num = 0;
                getCollectGoods(String.valueOf(num), String.valueOf(pageSize));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getCollectGoods(String.valueOf(num), String.valueOf(pageSize));
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }
}
